package com.example.aritcleservice.controller;


import com.example.aritcleservice.entity.Category;
import com.example.aritcleservice.service.ICategoryService;
import com.example.common.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.util.Collection;
import java.util.Collections;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 晨哥
 * @since 2024-05-01
 */
@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private ICategoryService categoryService;

    @RequestMapping("/add")
    public AjaxResult addCategory(Category category) {
        // 验证参数
        if (category == null || !StringUtils.hasLength(category.getName())) {
            return AjaxResult.fail(-1, "非法参数");
        }
        // 进行保存分类
        boolean result = categoryService.save(category);
        return AjaxResult.success(result);
    }

    @RequestMapping("/list")
    public AjaxResult getCategoryList() {
        List<Category> list = categoryService.list();
        if (list.size() == 0) {
            return AjaxResult.fail(0, "暂无数据！");
        }
        Collections.reverse(list);
        return AjaxResult.success(list);
    }

    @RequestMapping("/del")
    public AjaxResult delCategory(Integer cid) {
        // 参数判断
        if (cid == null || cid <= 0) {
            return AjaxResult.fail(-1, "非法参数!");
        }
        boolean flag = categoryService.removeById(cid);
        if (flag) {
            return AjaxResult.success("删除成功!");
        }
        return AjaxResult.fail(0, "删除失败!");
    }
}
